<template>
  <span :class="classes">
    <img :src="src" v-if="src">
    <span ref="children" :style="childrenStyle" v-else><slot></slot></span>
  </span>
</template>

<script>
  export default {
    name: 'VAvatar',
    props: {
      shape: {
        validator(value) {
          return ['circle', 'square'].indexOf(value) > -1;
        },
        default: 'circle',
      },
      size: {
        validator(value) {
          return ['small', 'large', 'default'].indexOf(value) > -1;
        },
        default: 'default',
      },
      src: {
        type: String,
      },
    },
    data() {
      return {
        scale: 1,
        isSlotShow: false,
      };
    },
    computed: {
      classes() {
        return [
          'v-avatar',
          `v-${this.shape}`,
          `v-${this.size}`,
          {
            'v-image': !!this.src,
          },
        ];
      },
      childrenStyle() {
        let style = {};
        if (this.isSlotShow) {
          style = {
            msTransform: `scale(${this.scale})`,
            WebkitTransform: `scale(${this.scale})`,
            transform: `scale(${this.scale})`,
            position: 'absolute',
            display: 'inline-block',
            left: `calc(50% - ${Math.round(this.$refs.children.offsetWidth / 2)}px)`,
          };
        }
        return style;
      },
    },
    methods: {
      setScale() {
        this.isSlotShow = !this.src;
        if (this.$slots.default) {
          const childrenWidth = this.$refs.children.offsetWidth;
          const avatarWidth = this.$el.getBoundingClientRect().width;
          // add 4px gap for each side to get better performance
          if (avatarWidth - 8 < childrenWidth) {
            this.scale = (avatarWidth - 8) / childrenWidth;
          } else {
            this.scale = 1;
          }
        }
      },
    },
    mounted() {
      this.setScale();
    },
    updated() {
      this.setScale();
    },
  };
</script>
